package com.ldf.jrtsp.parser;

import cn.hutool.core.util.StrUtil;

import static com.ldf.jrtsp.constants.RtspConstants.RTSP_DEFAULT_PORT;

/**
 * rtsp url解析
 *
 * @author lidaofu
 * @since 2024/6/19
 **/
public class RtspUrlParser {
    private String originalUrl;
    private String contentBase;
    private String host;
    private int port;
    private String username;
    private String password;
    private boolean isSsl;

    public RtspUrlParser(String rtspUrl) {
        String url;
        isSsl = rtspUrl.startsWith("rtsps");
        boolean existAuth = rtspUrl.contains("@");
        if (existAuth) {
            String[] parts = rtspUrl.split("@");
            String[] authParts = parts[0].substring(7).split(":");
            if (authParts.length == 2) {
                this.username = authParts[0];
                this.password = authParts[1];
            }
            url = parts[1];

        } else {
            url = rtspUrl.substring(7);
        }
        this.originalUrl = "rtsp://" + url;
        String[] split = url.split("/");
        int indexOf = split[0].indexOf(":");
        if (indexOf != -1) {
            this.host = split[0].substring(0, indexOf);
            this.port = Integer.parseInt(split[0].substring(indexOf + 1));
        } else {
            this.host = split[0];
            this.port = RTSP_DEFAULT_PORT;
            this.originalUrl= this.originalUrl.replace(host,host+":"+RTSP_DEFAULT_PORT);
        }

    }


    public String getOriginalUrl() {
        return originalUrl;
    }

    public void setOriginalUrl(String originalUrl) {
        this.originalUrl = originalUrl;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isSsl() {
        return isSsl;
    }

    public void setSsl(boolean ssl) {
        isSsl = ssl;
    }

    public String getContentBase() {
        if (StrUtil.isBlank(contentBase)){
            return originalUrl;
        }
        return contentBase;
    }

    public void setContentBase(String contentBase) {
        this.contentBase = contentBase;
    }
}
